package com.qdu.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qdu.entity.Assess;
import com.qdu.entity.Building;
import com.qdu.entity.Classroom;
import com.qdu.entity.CoursePlan;
import com.qdu.entity.CurrentTerm;
import com.qdu.entity.Grade;
import com.qdu.entity.LessionPlan;
import com.qdu.entity.Structure;
import com.qdu.entity.Student;
import com.qdu.entity.Teacher;
import com.qdu.entity.Term;
import com.qdu.entity.Users;
import com.qdu.service.AcadamyService;
import com.qdu.service.AssessService;
import com.qdu.service.BuildingService;
import com.qdu.service.ClassroomService;
import com.qdu.service.CoursePlanService;
import com.qdu.service.GradeService;
import com.qdu.service.LessionPlanService;
import com.qdu.service.StructureService;
import com.qdu.service.StudentService;
import com.qdu.service.TeacherService;
import com.qdu.service.TermService;
import com.qdu.service.UsersService;

@Controller
@RequestMapping("/teach")
public class TeacherController {

	@Autowired
	TermService termService;

	@Autowired
	CoursePlanService coursePlanService;

	@Autowired
	LessionPlanService lessionPlanService;

	@Autowired
	StudentService studentService;

	@Autowired
	GradeService gradeService;
	
	@Autowired
	ClassroomService classroomService;
	
	@Autowired
	BuildingService buildingService;
	
	@Autowired
	AssessService assessService;
	
	@Autowired
	TeacherService teacherService;
	
	@Autowired
	AcadamyService acadamyService;
	
	@Autowired
	StructureService structureService;
	
	@Autowired
    HttpSession session;
	
	@Autowired
	UsersService usersService;
	
	@Autowired
	PasswordEncoder pwdEncoder;

	@GetMapping("/selectCoursePlan")
	public String selectCoursePlan(Model model) {

		List<Integer> list = termService.selectAllTyear();
		model.addAttribute("yearList", list);
		return "Teacher/CoursePlan";
	}

	@GetMapping("/selectTermByTyear")
	@ResponseBody
	public List<Term> selectTermByTyear(int tyear) {
		List<Term> list = termService.selectCertainTermBytyear(tyear);
		return list;
	}

	@GetMapping("/selectCoursePlanByTermId")
	@ResponseBody
	public List<CoursePlan> selectTermByTermId(int termId, String tid) {
		List<LessionPlan> lessionPlanList = lessionPlanService.selectLessionPlanByTermId(termId);
		List<CoursePlan> list = new ArrayList<>();
		for (LessionPlan lessionPlan : lessionPlanList) {
			List<CoursePlan> coursePlanList = new ArrayList<>();
			coursePlanList = coursePlanService.selectCoursePlanByTidAndLpid(tid, lessionPlan.getLpid());
			if (coursePlanList.size() != 0) {
				list.addAll(coursePlanList);
			}
		}
		return list;
	}

	@GetMapping("/giveGrade")
	public String giveGrade(int cpid, int bid, Model model) {
		CurrentTerm currentTerm = (CurrentTerm) session.getAttribute("currentTerm");
		Term term = currentTerm.getTerm();
		if(term.getUploadgrade() == 1) {
			List<Student> stuList = studentService.selectAllStudentByBid(bid);
			model.addAttribute("stuList", stuList);
			model.addAttribute("cpid", cpid);
			List<Grade> gradeList = new ArrayList<>();
			for (Student stu : stuList) {
				Grade grade = gradeService.getGradeBySrollnoAndCpid(stu.getSrollno(), cpid);
				gradeList.add(grade);
			}
			model.addAttribute("gradeList", gradeList);
			model.addAttribute("bid", bid);
			model.addAttribute("cpid", cpid);
			return "Teacher/GiveGrade";
		}else {
			return "Teacher/Forbidden";
		}
	}

	@GetMapping("/giveGradeToStudent")
	@ResponseBody
	public void giveGradeToStudent(String srollno, int cpid, int grade, Model model) {
		int pass;
		if (grade >= 60)
			pass = 1;
		else
			pass = 0;
		Grade gra = new Grade(grade, pass);
		Grade gradeObject = gradeService.getGradeBySrollnoAndCpid(srollno, cpid);
		if (gradeObject == null) {
			gradeService.addGrade(gra, srollno, cpid, pass);
		} else {
			gra.setGradeId(gradeObject.getGradeId());
			gradeService.modifyGrade(gra, srollno, cpid, pass);
		}
	}
	
	@GetMapping("/toGetAssessResult")
	public String toGetAssessResult(Model model) {
		List<Integer> list = termService.selectAllTyear();
		model.addAttribute("yearList", list);
		return "Teacher/GetAssessResult";
	}
	
	
	@GetMapping("/getAssessResult")
	@ResponseBody
	public Assess getAssessResult(String tid, int termId) {
		Assess assess = assessService.getOneAssessByTidAndTermId(tid, termId);
		return assess;
	}

	
	@GetMapping("/downloadStudentByBid")
	public void download(int bid, HttpServletResponse response) {

		// 创建一张表，写入数据库数据
		XSSFWorkbook wb = studentService.showStudentByBid(bid);
		// execel表格的文件名
		String fileName = "学生列表.xlsx";
		// 声明输出流
		OutputStream os = null;

		try {
			// 解决名字乱码问题
			fileName = URLEncoder.encode(fileName, "UTF-8");
			// 将查询结果导出到excel，需要修改ContentType请求信息格式--application/vnd.ms-excel
			response.setContentType("application/vnd.ms-excel");
			// Content-disposition 提供打开/保存的对话框 attachment--作为附件下载
			response.setHeader("Content-disposition", "attachment;filename=" + fileName);
			// 获取输出流
			os = response.getOutputStream();
			// 将整理好的excel数据写入流中
			wb.write(os);
			// 清空缓冲区数据
			os.flush();
			// 关闭读写流
			os.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@GetMapping("/downloadGradeMould")
	public void downloadGradeMould(int bid, int cpid,HttpServletResponse response) throws IOException {
		
		// 创建一张表，写入数据库数据
				XSSFWorkbook wb = gradeService.downloadGradeMould(bid, cpid);
				// execel表格的文件名
				String fileName = "成绩上传模板.xlsx";
				// 声明输出流
				OutputStream os = null;

				try {
					// 解决名字乱码问题
					fileName = URLEncoder.encode(fileName, "UTF-8");
					// 将查询结果导出到excel，需要修改ContentType请求信息格式--application/vnd.ms-excel
					response.setContentType("application/vnd.ms-excel");
					// Content-disposition 提供打开/保存的对话框 attachment--作为附件下载
					response.setHeader("Content-disposition", "attachment;filename=" + fileName);
					// 获取输出流
					os = response.getOutputStream();
					// 将整理好的excel数据写入流中
					wb.write(os);
					// 清空缓冲区数据
					os.flush();
					// 关闭读写流
					os.close();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
	}
	
	@PostMapping("/uploadGrade")
	public String uploadGrade(MultipartFile file,int bid,int cpid, Model model) throws Exception {
		boolean flag = gradeService.uploadGrade(file);
		System.out.println(cpid);
		CurrentTerm currentTerm = (CurrentTerm) session.getAttribute("currentTerm");
		Term term = currentTerm.getTerm();
		if(term.getUploadgrade() == 1) {
			List<Student> stuList = studentService.selectAllStudentByBid(bid);
			model.addAttribute("stuList", stuList);
			model.addAttribute("cpid", cpid);
			List<Grade> gradeList = new ArrayList<>();
			for (Student stu : stuList) {
				Grade grade = gradeService.getGradeBySrollnoAndCpid(stu.getSrollno(), cpid);
				gradeList.add(grade);
			}
			model.addAttribute("gradeList", gradeList);
			model.addAttribute("bid", bid);
			model.addAttribute("cpid", cpid);
			return "Teacher/GiveGrade";
		}else {
			return "Teacher/Forbidden";
		}
	}

	
	@GetMapping("/modifyTeacherInfo/{tid}")
    public String modifyTeacherInfo(@PathVariable String tid, Model model) {
		model.addAttribute("acadamylist", acadamyService.selectAllAcadamy());
		model.addAttribute("teacher", teacherService.selectTeacherById(tid));
        return "Teacher/ModifyTeacherInfo";
    }
	@RequestMapping("/modifyTeacher")
	public String modifyTeacher(Teacher teacher,int acdmid,Model model) {
		teacherService.modifyTeacher(teacher, acdmid);
		String acdmname=acadamyService.selectAcadamyById(acdmid).getAcdmname();
		model.addAttribute("loginTeacher", teacher);
		model.addAttribute("acadamy", acdmname);
		return "User/UserInfo";
	}
	@RequestMapping("/User/UserInfo")
	public String toTeacherinfo(Model model) {
		String Tid=session.getAttribute("loginTeacherId").toString(); 
		Teacher teacher=teacherService.selectTeacherById(Tid);
		model.addAttribute("loginTeacher", teacher);
		model.addAttribute("acadamy", teacher.getAcadamy().getAcdmname());
		return "User/UserInfo";
	}
	@RequestMapping("/toModifyPassword")
	public String toIndex() {
		return "User/ModifyPassword";
	}
	
	@PostMapping("/teacherModifyPassword")
	@ResponseBody
	public boolean modifyPassword(String oldPassword,String newPassword,Model model){
		boolean flag= false;
		Teacher teacher = (Teacher) session.getAttribute("loginTeacher");
		Users user = usersService.getOneUserById(teacher.getTid());
		boolean check = pwdEncoder.matches(oldPassword, user.getUpassword());
		if(check) {
			user.setUpassword(pwdEncoder.encode(newPassword));
			usersService.modifyUser(user, 2);
			flag = true;
		}else {
			flag = false;
		}
		return flag;
	}
	
	
	
	@GetMapping("/toSchedule")
	public String toSchedule(Model model) {
		List<Integer> list = termService.selectAllTyear();
		model.addAttribute("yearList", list);
		List<Building> buildlist = buildingService.selectAllBuilding();
		model.addAttribute("buildlist", buildlist);
		return "Teacher/Schedule";
	}

	@GetMapping("/getScheduleByBidAndCycle")
	@ResponseBody
	public List<Structure> getScheduleByBidAndCycle(int bid, int termId, int cycle, Model model) {
		List<LessionPlan> lessList = lessionPlanService.selectLessionPlanByTermId(termId);
		List<CoursePlan> coursePlanList = new ArrayList<>();
		for (LessionPlan less : lessList) {
			CoursePlan coursePlan = coursePlanService.selectCoursePlanByThreeId(bid, less.getLpid());
			coursePlanList.add(coursePlan);
		}
		List<Structure> list = new ArrayList<>();
		for (CoursePlan coursePlan : coursePlanList) {
			List<Structure> strucList = structureService.getStructureByCoursePlanAndCycle(coursePlan.getCpid(), cycle);
			for (Structure struct : strucList) {
				list.add(struct);
			}
		}
		return list;
	}

	@GetMapping("/getScheduleByTid")
	@ResponseBody
	public List<Structure> getScheduleByTid(String tid, int termId, int cycle, Model model){
		List<LessionPlan> lessList = lessionPlanService.selectLessionPlanByTermId(termId);
		List<CoursePlan> coursePlanList = new ArrayList<>();
		for (LessionPlan less : lessList) {
			List<CoursePlan> coursePlanList2 = coursePlanService.selectCoursePlanByTidAndLpid(tid, less.getLpid());
			coursePlanList.addAll(coursePlanList2);
		}
		System.out.println(coursePlanList.size());
		List<Structure> list = new ArrayList<>();
		for (CoursePlan coursePlan : coursePlanList) {
			List<Structure> strucList = structureService.getStructureByCoursePlanAndCycle(coursePlan.getCpid(), cycle);
			for (Structure struct : strucList) {
				list.add(struct);
			}
		}
		return list;
	}
		
	
	@GetMapping("/getScheduleByClassrmIdAndCycle")
	@ResponseBody
	public List<Structure> getScheduleByClassrmIdAndCycle(int classrmid, int cycle, Model model) {
		List<Structure> list = structureService.getStructureByClassroomAndCycle(classrmid, cycle);
		return list;
	}
	@ResponseBody
	@GetMapping("/getClassrmByBuildid")
	public List<Classroom> getClassrmByBuildid(int buildingId){
		List<Classroom> classrmlist = classroomService.selectAllClassroom();
		List<Classroom> classrmlist2 = new ArrayList<Classroom>();
		for(Classroom c:classrmlist) {
			if(c.getBuilding().getBuildingId()==buildingId) {
				classrmlist2.add(c);
			}
		}
		return classrmlist2;
	}

	
}
